<?php
// +--------------+--------------+------+-----+---------+----------------+
// | Field        | Type         | Null | Key | Default | Extra          |
// +--------------+--------------+------+-----+---------+----------------+
// | id           | int(11)      | NO   | PRI | NULL    | auto_increment |
// | user_id      | int(11)      | YES  |     | 0       |                |
// | belongs_type | varchar(20)  | YES  |     |         |                |
// | belongs_id   | int(11)      | YES  |     | 0       |                |
// | title        | varchar(100) | YES  |     |         |                |
// | content      | text         | YES  |     | NULL    |                |
// | ip           | int(11)      | NO   |     | 0       |                |
// | status       | tinyint(1)   | NO   |     | 0       |                |
// | editor_id    | int(11)      | YES  |     | 0       |                |
// | create_time  | int(11)      | YES  |     | 0       |                |
// | update_time  | int(11)      | YES  |     | 0       |                |
// +--------------+--------------+------+-----+---------+----------------+
namespace app\common\model;
use think\Loader;
use think\Config;
use think\Db;
use think\Request;
class Comment extends Base{

  /**
   * 添加Comment
   * @Author zhanghong
   * @Date   2017-04-30
   * @param  array      $data Form提交的数据信息
   * @param  integer    $id   强制指定主键ID
   * @return array
   */
  public function saveItem($data){
    $res = ["status" => false, "msg" => "Comment保存失败"];
    $validate = Loader::validate("Comment");

    $request = Request::instance();
    $data["ip"] = ip2long($request->ip());
    $data["user_id"] = login_user_id();

    $seconds = Config::get("comment.interval_mins");
    $seconds = intval($seconds);
    $egt_time = time() - $seconds*60;
    $map = [
      "create_time" => [">=", $egt_time]
    ];
    if($data["user_id"]  > 0){
      $map["user_id"] = $data["user_id"];
    }else{
      $map["ip"] = $data["ip"];
    }
    if($this->where($map)->count()){
      $res["msg"] = "您评论的太频繁，请稍后再试";
      return $res;
    }

    if($validate->check($data)){
      $this->save($data);
      $res = ["status" => true, "msg" => "Comment保存成功"];
    }else{
      $res["msg"] = $validate->getError();
    }
    return $res;
  }

  /**
   * 删除Comment
   * @Author zhanghong
   * @Date   2017-09-17
   * @param  integer    $id   删除记录ID
   * @return array
   */
  public function delItem($id){
    $res = ["status" => false, "msg" => "删除失败"];

    $id = intval($id);
    $user_id = login_user_id();
    $del_count = $this->where("user_id", $user_id)->where("id", $id)->delete();

    if($del_count){
      $res = ["status" => true, "msg" => "删除成功"];
    }else{
      $res["msg"] = "删除评论不存在";
    }
    return $res;
  }

  /**
   * 前台用户查询单个belongs记录的评论
   * @Author zhanghong
   * @Date   2017-09-08
   * @param  string     $belongs_type     关联对象类型
   * @param  integer    $belongs_id     关联对象ID
   * @param  array      $page     页数
   * @param  integer    $page_rows 每页显示行数
   * @return \think\paginator\Collection
   */
  public function belongsSelect($belongs_type, $belongs_id, $page = 1, $page_rows = 5){
    $prefix = Config::get("database.prefix");

    $param = [
      "only_active" => 1,
      "belongs_type" => $belongs_type,
      "belongs_id" => $belongs_id,
      "parent_id" => 0,
    ];
    $this->searchWhere($param)
         ->join("{$prefix}user", "{$prefix}user.id={$prefix}comment.user_id", "LEFT");

    $options = $this->getOptions();
    $bind    = $this->getBind();
    $total_count = $this->count("*");

    $select_fields = [];
    $comment_fields = ["id", "user_id", "title", "content", "create_time"];
    foreach ($comment_fields as $idx => $key) {
      array_push($select_fields, "{$prefix}comment.{$key}");
    }
    array_push($select_fields, "{$prefix}user.nickname AS user_nickname");
    array_push($select_fields, "{$prefix}user.avatar AS user_avatar");

    $this->options($options)->bind($bind)->field($select_fields)
         ->order("{$prefix}comment.id DESC");

    $config["query"] = ["query" => $param];
    // 分页参数名是 page ，paginate方法内有获取到该值的方法
    $page = intval($page);
    if($page < 0){
      $page = 0;
    }
    $config["page"] = $page;
    $paginate = $this->paginate($page_rows, $total_count, $config);
    $list = $paginate->all();
    foreach ($list as $key => &$cmt) {
      $children_param = [
        "only_active" => 1,
        "belongs_type" => $belongs_type,
        "belongs_id" => $belongs_id,
        "parent_id" => $cmt["id"],
      ];
      $children = $this->searchWhere($children_param)
                       ->join("{$prefix}user", "{$prefix}user.id={$prefix}comment.user_id", "LEFT")
                       ->field($select_fields)
                       ->order("{$prefix}comment.id DESC")
                       ->select();
      $cmt["children"] = $children;
    }
    $paginate["list"] = $list;
    return $paginate;
  }

  /**
   * 管理员查询Article评论方法
   * @Author zhanghong
   * @Date   2017-09-08
   * @param  array      $param     查询参数
   * @param  integer    $page_rows 每页显示行数
   * @return \think\paginator\Collection
   */
  public function managerArticleSelect($param, $page_rows = 15){
    $prefix = Config::get("database.prefix");
    if(!is_array($param)){
      $param = [];
    }
    $param['belongs_type'] = 'Article';
    $this->searchWhere($param)
         ->join("{$prefix}user", "{$prefix}user.id={$prefix}comment.user_id", "LEFT")
         ->join("{$prefix}article", "{$prefix}comment.belongs_type='Article' AND {$prefix}article.id={$prefix}comment.belongs_id", "LEFT");

    $options = $this->getOptions();
    $bind    = $this->getBind();
    $total_count = $this->count("*");

    $select_fields = ["{$prefix}comment.*"];
    array_push($select_fields, "{$prefix}user.nickname AS user_nickname");
    array_push($select_fields, "{$prefix}user.avatar AS user_avatar");
    array_push($select_fields, "{$prefix}article.title AS belongs_title");
    array_push($select_fields, "{$prefix}article.type AS article_type");

    $this->options($options)->bind($bind)->field($select_fields)
         ->group("{$prefix}comment.id")->order("{$prefix}comment.id DESC");

    $config["query"] = ["query" => $param];
    // 分页参数名是 page ，paginate方法内有获取到该值的方法
    $page = 1;
    if(isset($param["page"])){
      $page = intval($param["page"]);
    }
    $config["page"] = $page;
    $paginate = $this->paginate($page_rows, $total_count, $config);
    return $paginate;
  }

  /**
   * 生成搜索条件
   * @Author zhanghong
   * @Date   2017-09-08
   * @param    array      $param 请求参数
   * @return   array             Select Map
   */
  private function searchWhere($param){
    $prefix = Config::get("database.prefix");
    if(!isset($param["belongs_type"]) || empty($param["belongs_type"])){
      $param["belongs_type"] = "empty";
    }

    foreach ($param as $key => $value) {
      if(is_null($value) || $value === ""){
        continue;
      }
      switch ($key) {
      case "belongs_type":
        $this->where("{$prefix}comment.belongs_type", $value);
        break;
      case "belongs_id":
      case "parent_id":
        $this->where("{$prefix}comment.{$key}", intval($value));
        break;
      case "only_active":
        $this->where("{$prefix}comment.status", 1);
        break;
      case "start_time":
        $this->where("{$prefix}comment.create_time < $value");
        break;
      case "end_time":
        $this->where("{$prefix}comment.create_time > $value");
        break;
      case "keyword":
        $keyword = "%{$value}%";
        $this->where("{$prefix}comment.title|{$prefix}comment.content|{$prefix}article.title", "like", $keyword);
        break;
      case "user_name":
        $keyword = "%{$value}%";
        $this->where("{$prefix}user.name|{$prefix}user.nickname|{$prefix}user.mobile", "like", $keyword);
        break;
      }
    }

    return $this;
  }
}